package com.love_weinuo.ui.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.BaseRequest;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.love_weinuo.R;
import com.love_weinuo.bean.LandNameBean;
import com.love_weinuo.bean.NearPindanCallBackBean;
import com.love_weinuo.bean.VersionCodeBean;
import com.love_weinuo.databinding.FragmentIndexBinding;
import com.love_weinuo.ui.activity.MyLandActivity;
import com.love_weinuo.ui.activity.PindanDetailActivity;
import com.love_weinuo.ui.activity.PindanZxingDescActivity;
import com.love_weinuo.ui.activity.SearchActivity;
import com.love_weinuo.ui.activity.WebViewActivity;
import com.love_weinuo.ui.adapter.IndexAdapter;
import com.love_weinuo.ui.adapter.OnItemClickListener;
import com.love_weinuo.ui.view.CycleViewPager;
import com.love_weinuo.ui.view.Info;
import com.love_weinuo.util.GsonUtil;
import com.love_weinuo.util.HTTPAPI;
import com.love_weinuo.util.LogUtil;
import com.love_weinuo.util.SpUtils;
import com.love_weinuo.util.ToastUtil;
import com.love_weinuo.util.VersionCodeUtil;
import com.love_weinuo.util.dialog.UpdadaApkDialog;
import com.love_weinuo.util.glideutil.GlideUtil;
import com.love_weinuo.util.listener.OnPindanPointListener;
import com.love_weinuo.util.listener.OnSelectLandListener;
import com.love_weinuo.util.updataapk.RxAppTool;
import com.love_weinuo.zxing.activity.CaptureActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static android.app.Activity.RESULT_OK;
import static com.love_weinuo.bean.Constants.REQUEST_CODE_COPYREASION;

/**
 * Created by Administrator
 * on 2019/2/21.
 */

public class IndexFragment extends BaseLazyFragment {

    FragmentIndexBinding binding;
    List<Info.ResultEntity.ResEntity> mList = new ArrayList<>();
    List<Info.ResultEntity.ResEntity> list = new ArrayList<>();

    List<NearPindanCallBackBean.ResultEntity.ResEntity> strs = new ArrayList<>();
    List<NearPindanCallBackBean.ResultEntity.ResEntity> pindanList = new ArrayList<NearPindanCallBackBean.ResultEntity.ResEntity>();
    IndexAdapter adapter;

    String landId = (String) SpUtils.get("module_index_land_id", "");
    LandNameBean landNameBean;

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(LayoutInflater.from(getActivity()), R.layout.fragment_index, container, false);
        binding.setFragment(this);
        return binding.getRoot();
    }

    @Override
    protected void onVisible() {
        LogUtil.e("indexFragment的onVisible()方法");
    }
    ReceiveBroadCast receiveBroadCast;

    @Override
    protected void lazyLoad() {
        landNameBean = new LandNameBean("");
        binding.rightImage.setOnClickListener(this);
        binding.tvModuleSearch.setOnClickListener(this);

        //        binding.nslModule.fling(0);
        //        binding.nslModule.smoothScrollTo(0, 0);
        //        binding.llModuleSelectLand.setOnClickListener(this);

        receiveBroadCast = new ReceiveBroadCast();
        IntentFilter filter = new IntentFilter();
        filter.addAction("moduleScan");
        getActivity().registerReceiver(receiveBroadCast, filter);

        getBanner();
    }

    public void getUpdataVersionCode() {
        HTTPAPI.getInstance().updataVersionCode(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("获取最新版本号成功" + s);
                //                binding.nslModule.fling(0);
                //                binding.nslModule.smoothScrollTo(0, 0);
                int vCode = VersionCodeUtil.getVersionCode(getActivity());
                VersionCodeBean bean = GsonUtil.GsonToBean(s, VersionCodeBean.class);
                double versionCode = Double.valueOf(bean.getResult().getVersion());
                if (vCode != versionCode) {
                    getNewApk();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("获取最新版本号失败" + e.getMessage());
            }
        });
    }

    UpdadaApkDialog dialog;

    public void getNewApk() {
        HTTPAPI.getInstance().getNewApk(new FileCallback() {
            @Override
            public void onBefore(BaseRequest request) {
                LogUtil.e("下载apk之前的操作");
                dialog = new UpdadaApkDialog(getActivity());
                dialog.show();
            }

            @Override
            public void downloadProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
                dialog.setBar(progress);
                dialog.setCancelable(false);
            }

            @Override
            public void onSuccess(File file, Call call, Response response) {
                RxAppTool.installApp(getActivity(), file.getAbsolutePath());
            }

            @Override
            public void onAfter(File file, Exception e) {
                dialog.dismiss();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("apk下载失败" + e.getMessage());
            }
        });
    }

    /**
     * 得到轮播图的View
     *
     * @param context
     * @param url
     * @return
     */
    public static View getImageView(Context context, String url) {
        RelativeLayout rl = new RelativeLayout(context);
        ImageView imageView = new ImageView(context);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(layoutParams);
        GlideUtil.setCircleMethod(context, url, imageView);
        ImageView backGround = new ImageView(context);
        backGround.setLayoutParams(layoutParams);
        backGround.setBackgroundResource(R.color.cycle_image_bg);
        rl.addView(imageView);
        rl.addView(backGround);
        return rl;
    }

    @Override
    public int setLayoutId() {
        return R.layout.fragment_index;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvModuleSearch:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
            case R.id.rightImage:
                startActivity(new Intent(getActivity(), CaptureActivity.class));
                break;
            case R.id.llModuleSelectLand:
                startActivityForResult(new Intent(getActivity(), MyLandActivity.class), REQUEST_CODE_COPYREASION);
                break;
            default:
        }
    }

    public void getBanner() {
        HTTPAPI.getInstance().getBanner(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("banner获取成功" + s);
                Info info = GsonUtil.GsonToBean(s, Info.class);
                list = info.getResult().getRes();
                mList.clear();
                mList.addAll(list);
                binding.cvpModule.setDelay(2000);
                binding.cvpModule.setData(mList, new CycleViewPager.ImageCycleViewListener() {
                    @Override
                    public void onImageClick(Info.ResultEntity.ResEntity info, int position, View imageView) {
                        LogUtil.e("点击位置" + position + " 跳转url-->" + info.getUrl());
                        Intent intent = new Intent(getActivity(), WebViewActivity.class);
                        intent.putExtra("module_web_url", info.getUrl());
                        startActivity(intent);
                    }
                });
                binding.recycler.setLayoutManager(new LinearLayoutManager(getActivity()));
                adapter = new IndexAdapter(getActivity(), strs, mList,landNameBean);
                binding.recycler.setAdapter(adapter);
                binding.recycler.setNestedScrollingEnabled(false);
                adapter.setOnItemClickLitener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        Intent intent = new Intent(getActivity(), PindanDetailActivity.class);
                        intent.putExtra("module_pindan_bean", strs.get(position));
                        intent.putExtra("module_from", "near");
                        startActivity(intent);
                    }

                    @Override
                    public void onItemLongClick(View view, int position) {

                    }
                });

                adapter.setOnSelectLandListener(new OnSelectLandListener() {
                    @Override
                    public void setOnSelectLandListener() {
                         startActivityForResult(new Intent(getActivity(),MyLandActivity.class),REQUEST_CODE_COPYREASION);
                    }
                });
                getNearPindan("", "", "");
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                LogUtil.e("banner获取失败" + e.getMessage());
            }
        });
    }

    String userId = (String) SpUtils.get("module_user_id", "");

    public void getNearPindan(String landId, String keyWord, String distance) {
        showProgressDialog("请稍候…");
        HTTPAPI.getInstance().getNearPindan(userId, landId, keyWord, distance, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("首页附近拼单获取-->" + s);
                cancelProgressDialog();
                getUpdataVersionCode();
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    int errorCode = jsonObject.getInt("errcode");
                    if (errorCode == 1) {
                        //                        binding.recycler.setVisibility(View.GONE);
                        //                        binding.ilModuleNothing.setVisibility(View.VISIBLE);
                        ToastUtil.showToast(jsonObject.getString("msg"));
                        return;
                    }
                    NearPindanCallBackBean bean = GsonUtil.GsonToBean(s, NearPindanCallBackBean.class);
                    switch (bean.getErrcode()) {
                        case 0:
                            pindanList.clear();
                            pindanList.addAll(bean.getResult().getRes());
                            if (pindanList.size() == 0) {
                                if (strs.size() != 0) {
                                    ToastUtil.showToast("暂无更多数据");
                                    return;
                                } else {
                                    //                                    binding.recycler.setVisibility(View.GONE);
                                    //                                    binding.ilModuleNothing.setVisibility(View.VISIBLE);
                                }
                            } else {
                                //                                binding.recycler.setVisibility(View.VISIBLE);
                                //                                binding.ilModuleNothing.setVisibility(View.GONE);
                                strs.clear();
                                strs.addAll(pindanList);
                                adapter.notifyDataSetChanged();
                                //                                binding.nslModule.fling(0);
                                //                                binding.nslModule.smoothScrollTo(0, 0);
                            }
                            break;
                        default:
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    LogUtil.e("json解析错误" + e.getMessage());
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                cancelProgressDialog();
                LogUtil.e("附近拼单获取失败" + e.getMessage());
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_COPYREASION:
                    landId = data.getStringExtra("module_land_id");
                    String landName = data.getStringExtra("module_land_name");
                    adapter.setLandname(landName);
                    SpUtils.put("module_index_land_id", landId);
                    getNearPindan(landId, "", "");
                    break;
                default:
            }
        } else {
            LogUtil.e("resultCode != RestltOK");
        }
    }

    /**
     * 声明接收扫描结果的广播，
     */
    class ReceiveBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("moduleScan".equals(intent.getAction())) {
                String result = intent.getStringExtra("pindanId");
                String answer = result.split("&")[0];
                String inviteCode = result.split("&")[1];
                SpUtils.put("module_broadcast_groupid", inviteCode);
                getActivity().startActivity(new Intent(getActivity(), PindanZxingDescActivity.class)
                        .putExtra("module_result", answer));
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (receiveBroadCast != null) {
            getActivity().unregisterReceiver(receiveBroadCast);
        }
    }

}
